import 'package:dio/dio.dart';
import 'package:memo_rcl/constants.dart';
import '../models/response_result.dart';

final dio = Dio();

/// 通用 GET 请求封装
Future<ResponseResult> _get(
  String url, {
  Map<String, dynamic>? queryParameters,
}) async {
  try {
    final response = await dio.get(url, queryParameters: queryParameters);

    if (response.statusCode == 200) {
      return ResponseResult.fromJson(response.data);
    } else {
      return ResponseResult(
        isSuccess: false,
        message: '请求失败，状态码: ${response.statusCode}',
        code: response.statusCode ?? 500,
      );
    }
  } on DioException catch (e) {
    String errorMsg = '网络请求失败';
    int errorCode = -1;

    if (e.response != null) {
      try {
        final errorData = e.response?.data;
        if (errorData is Map<String, dynamic>) {
          return ResponseResult.fromJson(errorData);
        }
      } catch (_) {}
      errorMsg = '服务器返回错误: ${e.response?.statusCode}';
      errorCode = e.response?.statusCode ?? -1;
    } else if (e.type == DioExceptionType.receiveTimeout) {
      errorMsg = '请求超时';
    } else if (e.type == DioExceptionType.cancel) {
      errorMsg = '请求被取消';
    } else if (e.type == DioExceptionType.badCertificate) {
      errorMsg = '证书错误';
    } else {
      errorMsg = '未知网络错误';
    }

    return ResponseResult(isSuccess: false, message: errorMsg, code: errorCode);
  } catch (e) {
    return ResponseResult(isSuccess: false, message: '发生未知错误: $e', code: -2);
  }
}

/// 通用 POST 请求封装
Future<ResponseResult> _post(
  String url, {
  Map<String, dynamic>? data,
  Map<String, dynamic>? queryParameters,
}) async {
  try {
    final response = await dio.post(
      url,
      data: data,
      queryParameters: queryParameters,
    );

    if (response.statusCode == 200) {
      return ResponseResult.fromJson(response.data);
    } else {
      return ResponseResult(
        isSuccess: false,
        message: '请求失败，状态码: ${response.statusCode}',
        code: response.statusCode ?? 500,
      );
    }
  } on DioException catch (e) {
    String errorMsg = '网络请求失败';
    int errorCode = -1;

    if (e.response != null) {
      try {
        final errorData = e.response?.data;
        if (errorData is Map<String, dynamic>) {
          return ResponseResult.fromJson(errorData);
        }
      } catch (_) {}
      errorMsg = '服务器返回错误: ${e.response?.statusCode}';
      errorCode = e.response?.statusCode ?? -1;
    } else if (e.type == DioExceptionType.receiveTimeout) {
      errorMsg = '请求超时';
    } else if (e.type == DioExceptionType.cancel) {
      errorMsg = '请求被取消';
    } else if (e.type == DioExceptionType.badCertificate) {
      errorMsg = '证书错误';
    } else {
      errorMsg = '未知网络错误';
    }

    return ResponseResult(isSuccess: false, message: errorMsg, code: errorCode);
  } catch (e) {
    return ResponseResult(isSuccess: false, message: '发生未知错误: $e', code: -2);
  }
}

//获取邮箱验证码code
Future<ResponseResult> fetchVerifyCode(String type, String emailAddress) {
  return _get(
    '${Constants.baseUrl}/user/verify_code',
    queryParameters: {'type': type, 'emailAddress': emailAddress},
  );
}

//获取图片验证码
Future<ResponseResult> verificationCode(String captchaKey) {
  return _get(
    '${Constants.baseUrl}/user/captcha',
    queryParameters: {'captchaKey': captchaKey},
  );
}

//注册账号
Future<ResponseResult> registerUser({
  required Map<String, dynamic> sobUser,
  required String emailCode,
  required String captcha,
  required String captchaKey,
}) {
  return _post(
    '${Constants.baseUrl}/user/register',
    data: sobUser,
    queryParameters: {
      'emailCode': emailCode,
      'captcha': captcha,
      'captchaKey': captchaKey,
    },
  );
}
